<style scoped lang="scss">
@import url('index.scss');
</style>
<template>
  <div class="app-container">
    <!--新模版样式-->
    <div class="topsearch">
      <el-row>
        <el-col :span="22" class="searchcol">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="采购单号" prop="purchaseno">
              <el-input v-model="queryParams.purchaseno" placeholder="请输入采购单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="生产厂家" prop="supplierId">
              <el-input v-model="queryParams.supplierId" placeholder="请输入生产厂家ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="生产批次" prop="supplierPici">
              <el-input v-model="queryParams.supplierPici" placeholder="请输入生产批次" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="采购合同号" prop="contractNo">
              <el-input v-model="queryParams.contractNo" placeholder="请输入采购合同号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="采购员" prop="purchaseUser">
              <el-input v-model="queryParams.purchaseUser" placeholder="请输入采购员" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="下单时间" prop="purchaseDate">
              <el-date-picker clearable v-model="queryParams.purchaseDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择下单时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="到货时间" prop="arriveDate">
              <el-date-picker clearable v-model="queryParams.arriveDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择要求到货时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button class="newButton" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22" class="rightcol">
          <div class="newbtn" @click="handleAdd" v-hasPermi="['system:purchase:add']">
            <img src="@/assets/images/add.svg" alt="">
            <span>新建</span>
          </div>
          <div class="newbtn" v-if="single == false" @click="handleUpdate" v-hasPermi="['system:purchase:edit']">
            <img src="@/assets/images/edit.svg" alt=""></img>
            <span>编辑</span>
          </div>
          <div class="newbtn" v-if="multiple == false" @click="handleDelete" v-hasPermi="['system:purchase:remove']">
            <img src="@/assets/images/del.svg" alt=""></img>
            <span>删除</span>
          </div>
          <div class="newbtn" @click="handleExport" v-hasPermi="['system:purchase:export']">
            <img src="@/assets/images/export.svg" alt=""></img>
            <span>导出</span>
          </div>
          <div class="newbtn" @click="getList">
            <img src="@/assets/images/refresh.svg" alt=""></img>
            <span>刷新</span>
          </div>
        </el-col>
      </el-row>
    </div>


    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单ID" width="100" align="center" prop="purchaseid" />
      <el-table-column label="采购单号" align="center" prop="purchaseno" />
      <el-table-column label="生产厂家ID" align="center" prop="supplierId">
        <template #default="scope">
          <!-- {{ manufacturerList }} -->
          <span>{{ manufacturerList.find(item => item.mid === scope.row.supplierId)?.mname || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产批次" align="center" prop="supplierPici" />
      <el-table-column label="采购合同号" align="center" prop="contractNo" />
      <el-table-column label="采购员" align="center" prop="purchaseUser" />
      <el-table-column label="下单时间" align="center" prop="purchaseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="要求到货时间" align="center" prop="arriveDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.arriveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="币种" align="center" prop="currency" />
      <el-table-column label="合同总价" align="center" prop="totalAmount" />
      <el-table-column label="采购单状态" align="center" prop="status">
        <template #default="scope">
          <span :class="{'text-success': scope.row.status === '1', 'text-danger': scope.row.status === '2'}">{{
            ha_purchase_status.find(item => item.value === scope.row.status)?.label || '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:purchase:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:purchase:remove']">删除</el-button>
          <el-button link class="newButton" icon="Check" @click="handleShen(scope.row)"
            v-hasPermi="['system:durguseplan:remove']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改采购单对话框 -->
    <el-dialog :title="title" v-model="open" width="66%" class="newDialog" @close="cancel">
      <el-form ref="purchaseRef" :model="form" :rules="rules" label-width="100px">

        <el-row :gutter="20" class="title">
          <el-col :span="12">
            基础信息
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购单号" prop="purchaseno">
              <el-input v-model="form.purchaseno" placeholder="请输入采购单号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请时间" prop="purchaseDate">
              <el-input v-model="form.purchaseDate" placeholder="请输入申请时间" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购单位" prop="purchaseUnit">
              <el-input v-model="form.purchaseUnit" placeholder="请输入采购单位" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购员" prop="purchaseUser">
              <el-input v-model="form.purchaseUser" placeholder="请输入采购员" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="title">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入采购合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入采购合同号" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20" class="title">
          <el-col :span="12">
            厂家信息
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="supplierId">
              <!-- <el-input v-model="form.supplierId" placeholder="请选择生产厂家" /> -->
              <el-select v-model="form.supplierId" placeholder="请选择生产厂家" clearable @change="handleSupplierChange">
                <el-option v-for="item in manufacturerList" :key="item.mid" :label="item.mname" :value="item.mid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactuser">
              <el-input v-model="form.contactuser" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactphone">
              <el-input v-model="form.contactphone" placeholder="请输入联系电弧" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <!-- <el-input v-model="form.supplierPici" placeholder="请输入生产批次" /> -->
              <el-date-picker clearable v-model="form.deliveryDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择交货日期" style="width: 100%;" :disabled-date="disabledDate" @change="handleDateChange">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>


        <el-row :gutter="20" class="title">
          <el-col :span="12">药品明细</el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24" style="padding-left: 110px; padding-right: 10px;">
            <el-table :data="drugTableData" border style="width: 100%">
              <el-table-column prop="id" label="ID" width="60"></el-table-column>
              <el-table-column label="药品名称">
                <template #default="scope">
                  <!-- <el-input v-model="scope.row.name" placeholder="药品名称" /> -->
                  <el-select v-model="scope.row.name" placeholder="请选择预约药品" clearable>
                    <el-option v-for="item in drugdictList" :key="item.drugid" :label="item.drugName"
                      :value="item.drugid"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="购买数量">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="0" @change="calcTotal(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="产品单价">
                <template #default="scope">
                  <el-input-number v-model="scope.row.unitPrice" :min="0" :precision="2"
                    @change="calcTotal(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template #default="scope">
                  <el-input v-model="scope.row.remark" placeholder="备注" />
                </template>
              </el-table-column>
              <el-table-column label="合计" width="180">
                <template #default="scope">
                  <span>{{ scope.row.total }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="deleteRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <el-col :span="12" style="padding-left: 110px; padding-right: 10px; margin-top: 20px;">
            <el-button class="newButton" @click="addItems">添加产品</el-button>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="title">
          <el-col :span="12">
            合同条款
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="到货时间" prop="arriveDate">
              <el-date-picker clearable v-model="form.arriveDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择要求到货时间" :disabled-date="disabledDateArrive">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付币种" prop="currency">
              <!-- <el-input v-model="form.currency" placeholder="请输入币种" /> -->
              <el-select v-model="form.currency" placeholder="请选择支付币种" clearable>
                <el-option v-for="item in ha_drug_pay" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <!-- <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" /> -->
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" clearable>
                <el-option v-for="item in ha_durg_paymethod" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总价" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入合同总价" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="4" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Purchase">
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/system/purchase"
import { listManufacturer, getManufacturer, delManufacturer, addManufacturer, updateManufacturer } from "@/api/system/manufacturer"
import { nextMinPurchaseNo } from "@/api/system/pcodelist"  //最小化获取接口 @鲍小伟20251201
import { sfMinNoBySeqid,useMinNoBySeqid } from "@/api/system/pcodelist"  //根据id释放端口号
import { ref } from 'vue';
import { listDrugdict } from "@/api/system/drugdict"  // 获取药品列表
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/system/item"

import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
import { useRouter } from 'vue-router'
const router = useRouter()
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { ha_drug_pay } = proxy.useDict('ha_drug_pay') //支付币种字典
const { ha_durg_paymethod } = proxy.useDict('ha_durg_paymethod') //支付币种字典
const { ha_purchase_status } = proxy.useDict('ha_purchase_status') //采购单状态字典


const purchaseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    purchaseno: null,
    supplierId: null,
    supplierPici: null,
    contractNo: null,
    contractName: null,
    purchaseUser: null,
    purchaseDate: null,
    deliveryDate: null, //交货日期
    arriveDate: null,
    currency: null,
    totalAmount: null,
    status: null,
  },
  rules: {
    purchaseno: [
      { required: true, message: '请输入采购单号', trigger: 'blur' },
    ],
    supplierId: [
      { required: true, message: '请选择生产厂家', trigger: 'blur' },
    ],
    arriveDate: [
      { required: true, message: '请选择到货时间', trigger: 'blur' },
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
//表格表单
const drugTableData = ref([
  // { id: 1, name: '', quantity: 0, unitPrice: 0, remark: '', total: 0 }
]);

const drugdictList = ref([]) //药品列表@鲍小伟20251203

function addItems() {
  const newId = drugTableData.value.length + 1;
  drugTableData.value.push({
    id: newId,
    name: '',
    quantity: 0,
    unitPrice: 0,
    remark: '',
    total: 0
  });
}

function calcTotal(row) {
  row.total = row.quantity * row.unitPrice;
}
function deleteRow(index) {
  drugTableData.value.splice(index, 1);
}

//获取药品的列表，直接从药品列表中选择 @鲍小伟20251203
function getDrugdictlist() {
  listDrugdict({
  pageNum: 1,
  pageSize: 1000,
  }).then(response => {
    // console.log(response)
    if(response.total>0){
      drugdictList.value = response.rows
    }else{
      drugdictList.value = []
    }
  })
}

// 监听时间戳变化 → 强制刷新
// console.log(router.currentRoute.value.query.t)
// watch(() => router.currentRoute.value.query.t, (newT) => {
//   if (newT) {
//     // 强制刷新数据
//     getList()
//   }
// })
// 监听药品表变化，实时计算合同总价
watch(
  drugTableData,
  () => {
    const sum = drugTableData.value.reduce((sum, row) => {
      return sum + Number(row.total);
    }, 0);
    form.value.totalAmount = sum.toFixed(2);
  },
  { deep: true }
);
//获取厂家的列表
const manufacturerList = ref([]) //厂家列表
const newqueryParam = {
  pageNum: 1,
  pageSize: 1000,
}
onMounted(async() => {
  // form.value.purchaseDate = new Date()
  // form.value.purchaseUser = 
  //获取厂家的列表
  listManufacturer(newqueryParam).then(response => {
    manufacturerList.value = response.rows
  })
  await getDrugdictlist() //获取药品列表
})
//不可用日期,到货时间的日期
function disabledDate(time) {
  // time 是候选日期对应的 Date 对象
   return time.getTime() < dayjs().startOf('day').valueOf()
}
function disabledDateArrive(time) {
  // time 是候选日期对应的 Date 对象
  return time.getTime() < dayjs(form.value.deliveryDate).startOf('day').valueOf()
}
// 到货时间选择器变化时，更新交货日期可选范围
function handleDateChange() {
   if (form.value.arriveDate) {
    form.value.arriveDate = null //清空到达时间重选
   }
}

//切换选择厂家带出联系人和电话信息
function handleSupplierChange() {
  //根据选中的厂家id查询联系人和电话
  console.log("厂家ID"+form.value.supplierId)
  //直接判断循环读取既可以了
  manufacturerList.value.forEach(item => {
    if (item.mid == form.value.supplierId) {
      form.value.contactuser = item.contactuser ? item.contactuser : ""
      form.value.contactphone = item.contactphone ? item.contactphone : ""
    }
  })
}

/** 查询采购单列表 */
function getList() {
  loading.value = true
  listPurchase(queryParams.value).then(response => {
    purchaseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function handleShen(row) {
  //审核采购单
  console.log(row)

}

// 取消按钮
async function cancel() {
 // 1.先保存 seqid（重置前）
  const sid = form.value.allPurchaseInfo?.seqid
  console.log('待释放 seqid：', sid)
  // 2.异步释放（不依赖重置后的 form）
  if(sid) {
    await sfMinNoBySeqid(sid)
  }
    open.value = false
    reset()
}

// 表单重置
function reset() {
  form.value = {
    purchaseid: null,
    purchaseno: null,
    supplierId: null,
    supplierPici: null,
    contractNo: null,
    contractName: null,
    purchaseUser: userStore.name, //申请人为当前登录用户
    purchaseDate: dayjs().format('YYYY-MM-DD HH:mm:ss'), //当前时间时分秒,,
    deliveryDate: null, //交货日期
    arriveDate: null,
    currency: null,
    totalAmount: null,
    status: '1',  //默认状态为1，待审核
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    allPurchaseInfo: null, // 采购单详情
  }
  drugTableData.value = [] // 明细表也重置一下@鲍小伟20251203
  proxy.resetForm("purchaseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.purchaseid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
async function handleAdd() {
  //不用弹出，用一个新的界面
 reset()
 open.value = true
 title.value = "添加采购单"
 //点击的时候，获取最小化的采购单号并锁定单号
//  nextMinPurchaseNo().then(response => {
//   console.log(response)
//   form.value.purchaseno = response.data.buildNo()
//  })
  const res = await nextMinPurchaseNo();
  console.log(res.data);   // 打印整个对象
  form.value.purchaseno = res.data.purchaseNo;
  form.value.allPurchaseInfo = res.data; //申请人为当前登录用户
//  router.push({
//     path: '/medicine/purchase/add'
//   })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _purchaseid = row.purchaseid || ids.value
  getPurchase(_purchaseid).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改采购单"
    //调取出生产厂家带出的联系人等信息@鲍小伟20251203
    console.log(form.value)
    manufacturerList.value.forEach(item => {
      if (item.mid == form.value.supplierId) {
        form.value.contactuser = item.contactuser ? item.contactuser : ""
        form.value.contactphone = item.contactphone ? item.contactphone : ""
      }
    })
    //end
    //编辑的时候，也需要调出采购单的明细@鲍小伟20251203

    //调出采购单明细end
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["purchaseRef"].validate(valid => {
    if (valid) {
      if (form.value.purchaseid != null) {
        updatePurchase(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // console.log(form.value)
        // console.log(drugTableData.value)
        addPurchase(form.value).then( async response => {
          // proxy.$modal.msgSuccess("新增成功")
          console.log(response)
          if (response.code == 200) {
            proxy.$modal.msgSuccess("新增成功")
            //变更一下使用的状态
            useMinNoBySeqid(form.value.allPurchaseInfo.seqid).then(response => {
              console.log(response)
            })
            //end
            // 循环建立新明细并插入
            const purchaseid = response.data.purchaseid;   // 主键已回填
            for (const item of drugTableData.value) {
              const detail = {
                purchaseid: purchaseid,
                drugid: item.name,              // 药品 ID
                unitNum: item.quantity,         // 数量
                amount: item.unitPrice,         // 单价
                remark: item.remark,
                createBy: userStore.name,
                createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                updateBy: userStore.name,
                updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
              };
              await addItem(detail);   // 逐条插入
            }
          }
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _purchaseids = row.purchaseid || ids.value
  proxy.$modal.confirm('是否确认删除采购单编号为"' + _purchaseids + '"的数据项？').then(function() {
    return delPurchase(_purchaseids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/purchase/export', {
    ...queryParams.value
  }, `purchase_${new Date().getTime()}.xlsx`)
}

getList()
</script>
